import axios from 'axios';
import { TOKEN_NAME, AUTH_WHITE_LIST } from './conf';

// 请求超时时间
axios.defaults.timeout = 50000;

// // 请求拦截
// axios.interceptors.request.use(
//   (config) => {
//     if (config.url.includes("login")) {
//       return config;
//     }
//     config.headers["Authorization"] = "Bearer " + (Store.getters["user/token"] || "");
//     return config;
//   },
//   (error) => {
//     return error;
//   }
// );

class HttpBase {
  _TOKEN;
  constructor() {}

  _setToken(token) {
    window.localStorage.setItem(TOKEN_NAME, btoa(token));
    this._TOKEN = token;
  }

  _getToken() {
    const token = window.localStorage.getItem(TOKEN_NAME);
    this._TOKEN = this._TOKEN ? this._TOKEN : atob(token);
    return this._TOKEN;
  }

  _deleteToken() {
    window.localStorage.removeItem(TOKEN_NAME);
    this._TOKEN = null;
  }
  /**
   * 获取token headers
   * @param {*} token
   * @returns Object {Authorization：x}
   */
  getTokenHeaders(url, token = null) {
    // 鉴权白名单
    if (AUTH_WHITE_LIST.includes(url)) {
      return {};
    }
    const TOKEN = token ? token : this._TOKEN;
    // 防重放攻击timestamp，nonce
    return {
      timestamp: new Date().getTime(),
      nonce: Math.floor(Math.random() * 10000),
      Authorization: 'Bearer ' + (TOKEN || '')
    };
  }

  _http() {
    return axios;
  }

  /**
   * url 转化proxy 默认值import.meta.env.VITE_APP_BASE_URL
   * @param {*} url
   * @param {*} proxyUrl
   * @returns string
   */
  _urlTransform(url, proxyUrl = null) {
    proxyUrl = proxyUrl ? proxyUrl : import.meta.env.VITE_APP_BASE_URL;
    return proxyUrl + url;
  }

  _formDataTransform(params, bool = true) {
    if (!bool) {
      return params;
    }
    const formData = new FormData();
    for (const key in params) {
      const value = params[key];
      typeof value === 'object' ? formData.append(key, JSON.stringify(value)) : formData.append(key, value);
    }
    return formData;
  }

  /**
   * _get 请求
   * @param {*} url
   * @param {*} params
   * @param {*} headers
   * @param {*} urlPrex url前缀
   * @returns Promise
   */
  _get(url, params, headers = {}, proxyUrl) {
    const HEADERS = {
      'Content-Type': 'application/json;charset=UTF-8',
      ...this.getTokenHeaders(url),
      ...headers
    };
    const _url = this._urlTransform(url, proxyUrl);
    return axios.get(_url, { params, headers: { ...HEADERS } });
  }

  /**
   * _post form 表单
   * @param {*} url
   * @param {*} params
   * @param {*} headers
   * @returns
   */
  _post(url, params, headers = {}, proxyUrl) {
    const HEADERS = {
      'Content-Type': 'multipart/form-data;charset=UTF-8',
      ...this.getTokenHeaders(url),
      ...headers
    };
    const _url = this._urlTransform(url, proxyUrl);
    const formData = this._formDataTransform(params);
    return axios.post(_url, formData, { headers: { ...HEADERS } });
  }

  /**
   * _postJSON json 表单提交
   * @param {*} url
   * @param {*} params
   * @param {*} headers
   * @returns
   */
  _postJSON(url, params, headers = {}, proxyUrl) {
    const HEADERS = {
      'Content-Type': 'application/json;charset=UTF-8',
      ...this.getTokenHeaders(url),
      ...headers
    };
    const _url = this._urlTransform(url, proxyUrl);
    return axios.post(_url, params, { headers: { ...HEADERS } });
  }

  /**
   * file 文件上传
   * @param {*} url
   * @param {*} params
   * @param {*} headers
   * @returns
   */
  _postFile(url, params, headers = {}, proxyUrl) {
    const HEADERS = {
      'Content-Type': 'multipart/form-data;charset=UTF-8',
      ...this.getTokenHeaders(url),
      ...headers
    };
    const _url = this._urlTransform(url, proxyUrl);
    return axios.post(_url, params, { headers: { ...HEADERS } });
  }
  /**
   * _getFile 下载文件
   * @param {*} url
   * @param {*} params
   * @param {*} headers
   * @returns
   */
  _downFile(url, params, headers = {}, proxyUrl) {
    const HEADERS = {
      ...this.getTokenHeaders(url),
      ...headers
    };
    const _url = this._urlTransform(url, proxyUrl);
    return axios({
      method: 'get',
      url: _url,
      // data: formData,
      params,
      responseType: 'blob',
      headers: HEADERS
    });
  }
}

export default HttpBase;
